package com.chenzhou.qx.library.adid;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.util.Log;

import com.google.android.gms.ads.identifier.AdvertisingIdClient;

import java.util.concurrent.Executors;

public class AdIdUtil {

    private static final String TAG = "AdidUtil";
    private static final String PREFERENCE_NAME = "qx_adid";
    private static final String KEY_ADID = "KEY_ADID";

    public interface OnAdIdListener {
        default void success(String adid) {
        }

        default void error(String error) {
        }
    }

    public static void init(final Context context) {
        init(context, null);
    }

    public static void init(final Context context, OnAdIdListener listener) {

        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    AdvertisingIdClient.Info info = AdvertisingIdClient.getAdvertisingIdInfo(context);
                    String advertisingId = info.getId();
                    Log.e(TAG, "advertisingId = " + advertisingId);
                    AdIdUtil.putString(context, KEY_ADID, advertisingId);
                    if (listener != null) {
                        listener.success(advertisingId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.error(e.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 获取ADID，没有则返回空字符串
     */
    public static String getAdId(Context context) {
        return getString(context, KEY_ADID, "");
    }

    /**
     * 获取AndroidID
     */
    public static String getAndroidId(Context context) {
        try {
            @SuppressLint("HardwareIds")
            String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            return androidId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String getString(Context context, String key, String defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getString(key, defaultValue);
    }

    private static boolean putString(Context context, String key, String value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        return editor.commit();
    }

}
